package com.example.car.adapter

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.car.NewInfoActivity
import com.example.car.R
import com.example.car.bean.NewsListBean
import com.example.car.databinding.ItemNewsListBinding

class NewsListAdapter(var ctx: Context) : RecyclerView.Adapter<NewsListAdapter.ViewHolder>() {
    private lateinit var binding: ItemNewsListBinding


    inner class ViewHolder : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        binding = ItemNewsListBinding.inflate(inflater, parent, false)
        return ViewHolder()
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val bind = ItemNewsListBinding.bind(holder.itemView)
        bind.apply {
            val data: NewsListBean.Result.Data = differ.currentList[position]
            title.text = data.title
            authorName.text = data.author_name
            date.text = data.date

            Glide.with(binding.root)
                .load(data.thumbnail_pic_s)
                .error(R.mipmap.img_error)
                .into(thumbnailPicS)

            holder.itemView.setOnClickListener {
                val intent = Intent(ctx, NewInfoActivity::class.java)
                Log.d("TAG", "DATA:" + data.toString())
                intent.putExtra("data", data)
                ctx.startActivity(intent)
            }

        }
    }

    override fun getItemCount() = differ.currentList.size

    val differ = AsyncListDiffer(this, object : DiffUtil.ItemCallback<NewsListBean.Result.Data>() {
        override fun areItemsTheSame(
            oldItem: NewsListBean.Result.Data,
            newItem: NewsListBean.Result.Data
        ): Boolean {
            return oldItem.uniquekey == newItem.uniquekey
        }

        override fun areContentsTheSame(
            oldItem: NewsListBean.Result.Data,
            newItem: NewsListBean.Result.Data
        ): Boolean {
            return oldItem == newItem
        }
    })

    fun addData(list: List<NewsListBean.Result.Data>) {
        differ.submitList(list)
        notifyDataSetChanged()
    }
}